from turbogears import identity
from mnemoply.model.auth import Menu
import copy, time


class menu(object):
    """
        Class for create tree-menu, which has methods for create and
        check visibility for current user
    """
    mainmenu=[]

    def __init__(self, select):
        self.mainmenu = self.create_menu(select)
        
    def create_menu(self,select):
        mainmenu = []
        items ={}
        for menu in select:
            item=dict(
                      href=menu.href,
                      name=menu.name,
                      id = menu.id,
                      ordinal=menu.ordinal,
                      )
            exist = items.has_key(menu.id)
            items[menu.id] = item
            if not exist:
                items[menu.id]['subs']=[]
            
            if menu.parent is None:
                mainmenu+= [items[menu.id]]
            else:
                if not items.has_key(menu.parentID):
                    items[menu.parentID]=dict(subs=[])
                items[menu.parentID]['subs'] +=[item]
        return mainmenu
    

    def get_menu_with_permission(self):
        result = copy.deepcopy(self)
        x = [m for m in result.mainmenu if result.check_permission(m)]
        return x

    def check_permission(self,one_menu):
        """
            IMPORTANT! This function changes its own argument
        """
        if not one_menu['subs']:
            href= one_menu['href']
            if identity.in_group('dba'):
                return True
            if identity.has_permission(href) or identity.has_permission(href+'all') :
                return True
            return False

        subs = [m for m in one_menu['subs'] if self.check_permission(m)]
        one_menu['subs'] = subs
        return len(subs)


class mainmenu_dynamic(object):
    """
        Class contains singleton object for main menu (all points). 
    """
    _instance = None

    @classmethod
    def instance(cls):
        if cls._instance is None or \
                Menu.is_need_recreate():
            cls._instance = menu(list(Menu.select(orderBy=['parent_id','ordinal'])))
        return cls._instance

    def __init__(self):
        self._instance = self.instance()

    def get_menu_with_permission(self):
        """
            return copy of object without denyed points 
        """
        return _instance.get_menu_with_permission()

        
